<template>
    <span>
        <el-upload class="icon-upload"
                   v-if="!formItem || !formData || !formData[formItem.prop]"
                   drag
                   multiple
                   :action="`/api/file/upload?purpose=${iconPurpose}&ownerId=0`"
                   :show-file-list="false"
                   :on-success="iconUploadSuccess">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处, </div>
            <div class="el-upload__text">或
                <em>点击上传</em>
            </div>
        </el-upload>
        <div style="display:inline-block;"
             v-if="formData[formItem.prop]">
            <img :src="`/api${formData[formItem.prop]}`"
                 width="80" />
            <i class="icon-delete el-icon-delete"
               @click="iconDelete" />
        </div>
    </span>
</template>

<script>
    import Vue from 'vue'
    export default {
        name: 'iconUpload',
        props: ['prop', 'purpose', 'data', 'delete', 'uploadSuccess'],
        data() {
            return {
                iconPurpose: this.purpose,
                formItem: this.prop,
                formData: this.data ? this.data : {}
            }
        },
        mounted() {
            console.log('iconUpload', this.formItem)
        },
        methods: {
            iconDelete() {
                const fileUrl = this.formData[this.formItem.prop]
                const fileId = fileUrl && fileUrl.replace('/file/image/', '')
                this.formData[this.formItem.prop] = ''
                this.delete && this.delete(fileId, this.formData)
            },
            iconUploadSuccess(res) {
                Vue.set(this.formData, this.formItem.prop, res.fileUrl)
                console.log('iconUploadSuccess', this.formData)
                this.uploadSuccess && this.uploadSuccess(this.formData)
            }
        }
    }
</script>

<style lang="less">
.icon-upload {
    width: 200px;
    height: 200px;
    .el-upload {
        width: 200px;
        height: 200px;
    }
    .el-upload-dragger {
        width: 200px;
        height: 200px;
    }
}
.icon-delete {
    cursor: pointer;
}
.icon-delete:hover {
    font-size: 24px;
    color: var(--global-color);
}
</style>